package com.service.scheduling.task;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.service.dao.constants.ConfigConstants;
import com.service.dao.enums.*;
import com.service.dao.mapper.OrderProductHrComboDetailsMapper;
import com.service.dao.model.Coins;
import com.service.dao.model.Member;
import com.service.dao.model.MemberGradeConfig;
import com.service.dao.model.SysConfig;
import com.service.scheduling.dto.MemberStoreChange;
import com.service.scheduling.service.*;
import com.service.scheduling.support.MemberStoreLockUtils;
import com.service.scheduling.utils.DateUtil;
import com.service.scheduling.utils.MathUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全网算力加权分红
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class HrComboRateNetworkReleaseTask {
	@Autowired
	private MemberService memberService;
	@Autowired
	private MemberStoreLockUtils memberStoreLockUtils;
	@Autowired
	private MemberStoreService memberStoreService;
	@Autowired
	private OrderProductHrComboService orderProductHrComboService;
	@Autowired
	private MemberJAService jaService;
	@Autowired
	private ConfigService configService;
	@Autowired
	private CoinService coinService;
	@Autowired
	private MemberGradeConfigService gradeConfigService;
	@Autowired
	private OrderProductHrComboDetailsMapper orderProductHrComboDetailsMapper;

	private static BigDecimal baseNum = new BigDecimal(100L);

	@Scheduled(cron = "0 20 0 * * ?")
//	@Scheduled(cron = "0 */15 * * * ?")
	public void doCalculate() {
		log.info("#################全网矿池加权分红任务-开始");
		String minerStatus = configService.getByConfigName(ConfigConstants.MINER_STATUS).getConfValue();
		if (MinerStatusEnum.OFF.equals(minerStatus)) {
			log.info("矿机暂停运行......");
			return;
		}
		String pattern = "yyyy-MM-dd";
		Date current = new Date();
		Date yesterday = DateUtil.getDayOfStart(DateUtils.addDays(current, -1));
		String yesterdayStr = DateFormatUtils.format(yesterday, pattern);
		//获取币种列表
		List<Coins> coinsList = coinService.list(new QueryWrapper<Coins>().lambda()
			.eq(Coins::getCoinStatus, CommonStatusEnums.ACTIVE.getCode())
		);
		if(ObjectUtils.isEmpty(coinsList)){
			log.info("币种全部关闭，退出全网加权分红");
			return;
		}
		SysConfig comShareConf = configService.getByConfigName(ConfigConstants.COM_FEE_SHARE_RATE);
		BigDecimal comFeeShareRate = MathUtil.div(MathUtil.parseBigDecimal(comShareConf.getConfValue()),baseNum,4);
		coinsList.forEach(item->{
			//统计全网今日手续费收益
			BigDecimal totalAllNetworkSomeDayReleaseNum = jaService.totalAllNetworkSomeDayReleaseNum(MemberJAType.getComFeeType(), item.getCoinName(),  current);
			totalAllNetworkSomeDayReleaseNum = totalAllNetworkSomeDayReleaseNum.multiply(comFeeShareRate);
			log.info("昨日平台{}全网托管费收益{}",item.getCoinName(),totalAllNetworkSomeDayReleaseNum);
			//今日全网矿池奖励基数
			BigDecimal networkRewardNum = MathUtil.mul(totalAllNetworkSomeDayReleaseNum,totalAllNetworkSomeDayReleaseNum,8);
			if (networkRewardNum.compareTo(BigDecimal.ZERO) <= 0) {
				log.info("平台全网{}托管费收益为0，全网矿池加权分红退出", yesterdayStr);
				return;
			}
			log.info("作日全网矿池奖励基数{}",networkRewardNum);
			List<MemberGradeConfig> memberGradeConfigs = gradeConfigService.list(new QueryWrapper<MemberGradeConfig>().lambda()
				.gt(MemberGradeConfig::getNetworkMiningRewardRate,BigDecimal.ZERO)
			);
			if(ObjectUtils.isEmpty(memberGradeConfigs)){
				log.info("暂无等级设置全网分红比例");
				return;
			}
			List<Integer> gradeIds = memberGradeConfigs.stream().map(MemberGradeConfig::getId).collect(Collectors.toList());
			List<Member> memberList = memberService.listByGradeList(gradeIds);
			if(ObjectUtils.isEmpty(memberList)){
				log.info("暂无用户达到全网分红条件");
				return;
			}
			memberList.forEach(member -> {
				//获取用户的vip等级配置信息
				MemberGradeConfig gradeConfig = gradeConfigService.getMemberGradeConfig(member.getVipGrade());
				BigDecimal networkMiningPoolRewardRate = MathUtil.div(gradeConfig.getNetworkMiningRewardRate(), baseNum,4);
				BigDecimal lastRewardNum = networkRewardNum.multiply(networkMiningPoolRewardRate);
				if (lastRewardNum.compareTo(BigDecimal.ZERO) == 0) {
					log.info("用户id:{}今日全网矿池分红数量为0", item.getId());
					return;
				}
				try{
					boolean isLock = memberStoreLockUtils.lock(member.getId(), item.getId());
					if (!isLock) {
						return;
					}
					Integer jaId = memberStoreService.changeMemberStore(
							MemberStoreChange.builder()
									.memberId(member.getId())
									.coinsId(item.getId())
									.coinsName(item.getCoinName())
									.jaType(MemberJAType.NETWORK_REWARD)
									.changeNum(lastRewardNum)
									.remark(yesterdayStr + MemberJAType.NETWORK_REWARD.getMsg() + " 数量：" + lastRewardNum)
									.build());
				}finally {
					memberStoreLockUtils.unlock(member.getId(), item.getId());
				}
			});
		});
		log.info("全网算力加权分红任务-结束#################");
	}
}
